﻿using Ninject;
using QuickChat_Service.Helpers;
using QuickChat_Service.Repositories;
using QuickChat_Service.Repositories.Database;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace QuickChat_Service.Controllers
{
    public class ChatRoomsController : ApiController
    {
        private IChatServiceUnitOfWork UoW{get; set;}

        public ChatRoomsController()
        {
            var kernel = new StandardKernel(new QuickChatDependencyInjectionModule());
            UoW = kernel.Get<IChatServiceUnitOfWork>();
        }

        public ChatRoomsController(IChatServiceUnitOfWork uoW)
        {
            UoW = uoW;
        }

        // GET api/talkers
        public HttpResponseMessage Get()
        {
            var chatRooms = UoW.chatRoomRepo.GetAll();

            if (chatRooms == null)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }
            return Request.CreateResponse<IQueryable<ChatRoom>>(HttpStatusCode.OK, chatRooms);
        }

        // GET api/talkers/5
        public HttpResponseMessage Get(int id)
        {
            var chatRoom = UoW.chatRoomRepo.GetById(id);

            if (chatRoom == null)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }

            return Request.CreateResponse<ChatRoom>(HttpStatusCode.OK, chatRoom);  
        }

        // POST api/talkers
        public HttpResponseMessage Post(ChatRoom chatRoom)
        {
            if (chatRoom == null || chatRoom.CreatorsId == null)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "You must atleat specify a CreatorsId"));
            }

            chatRoom.CreatedTime = DateTime.UtcNow;
            UoW.chatRoomRepo.Add(chatRoom);

            var response = Request.CreateResponse<ChatRoom>(HttpStatusCode.Created, chatRoom);
            response.Headers.Location = new Uri(Request.RequestUri.Authority + "/api/ChatRooms/" + chatRoom.RoomId.ToString());

            return response;
        }

        // DELETE api/talkers/5
        public HttpResponseMessage Delete(int id)
        {
            if (id == null)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "You must suppply an id"));
            }

            bool thereAreActiveUsersInRoom = UoW.chatRoomRepo.GetById(id).Talkers.Any();

            if (thereAreActiveUsersInRoom)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Forbidden, "You cannot delete a room with active users in it"));
            }

            UoW.chatRoomRepo.Delete(id);

            return Request.CreateResponse(HttpStatusCode.NoContent);
        }
    }
}
